package cn.itsource.pethome.system.atools.registerAndLogin.controller;

import cn.itsource.pethome.config.WeChatConfig;
import cn.itsource.pethome.constants.BaseConstants;
import cn.itsource.pethome.system.atools.registerAndLogin.domain.PhoneRegister;
import cn.itsource.pethome.system.atools.registerAndLogin.domain.WeChatLogin;
import cn.itsource.pethome.system.atools.registerAndLogin.domain.WechatBinder;
import cn.itsource.pethome.system.logininfo.domain.LoginDTO;
import cn.itsource.pethome.system.logininfo.service.ILogininfoService;
import cn.itsource.pethome.system.user.domain.User;
import cn.itsource.pethome.system.user.service.IUserService;
import cn.itsource.pethome.system.wxuser.domain.Wxuser;
import cn.itsource.pethome.system.wxuser.service.IWxuserService;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.BusinessException;
import cn.itsource.pethome.utils.HttpClientUtils;
import cn.itsource.pethome.utils.MassageUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author:R
 * @Date:2023/1/31 19:30
 * Description 微信登录
 */
@RestController
@RequestMapping("/login")
@Api(value = "前台登录API",description="前台登录的功能")
public class LoginController {
    @Resource
    private WeChatConfig weChatConfig;
    @Resource
    private IWxuserService wxuserService;
    @Resource
    private IUserService userService;
    @Resource
    private ILogininfoService logininfoService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 1.获取前端传递过来的授权码
     * 2.通过授权码获取令牌（包含unionid）
     * 3.通过unionid查询微信用户表，
     *      3.1如果无结果，证明用户第一次来，保存用户信息到微信用户表，然后跳转绑定信息页面
     *      3.2有结果：判断user_id字段是否有信息
     *          有信息，获取信息，登录
     *          无信息，跳转绑定页面
     * @param weChatLogin
     * @return
     */
    @PostMapping("/wechat")
    @ApiOperation(value = "微信登录的接口")
    public AjaxResult weChatLogin(@RequestBody WeChatLogin weChatLogin){
        //获取授权码
        String code = weChatLogin.getCode();
        if ("".equals(code) || code == null)
            return AjaxResult.error().setMsg("非法访问！");
        //获取令牌
        String tokenUrl = weChatConfig.getAccessToken(code);
        String tokenResult = HttpClientUtils.httpGet(tokenUrl);//发送请求
        JSONObject jsonObject = JSONObject.parseObject(tokenResult);//转json对象

        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        String unionid = jsonObject.getString("unionid");

        Wxuser wxuser = wxuserService.findByUnionId(unionid);
        if (wxuser == null){//证明第一次用微信登录本系统,获取用户信息，然后存入数据库
            //获取用户信息
            String userinfoUrl = weChatConfig.getUserinfo(accessToken, openid);
            String userResult = HttpClientUtils.httpGet(userinfoUrl);
            Wxuser wxuser1 = JSONObject.parseObject(userResult, Wxuser.class);
            wxuserService.add(wxuser1);
            //跳转绑定页面
            return AjaxResult.success().setMsg("NoBind").setData(unionid);
        }else {
            if (wxuser.getUserId() == null){//之前注册过，但是未绑定用户信息
                return AjaxResult.success().setMsg("NoBind").setData(unionid);
            }else { //之前登录过，有用户信息，直接登录
                Long userId = wxuser.getUserId();
                User user = userService.findOne(userId);
                LoginDTO loginDTO = new LoginDTO();
                loginDTO.setPassword(user.getPassword());
                loginDTO.setUsername(user.getUsername());
                loginDTO.setType(BaseConstants.Login.TYPE_USER);
                loginDTO.setAutoLogin(true);
                return logininfoService.account(loginDTO);
            }
        }
    }

    @PostMapping("/wechat/binder")
    @ApiOperation(value = "微信绑定的接口")
    public AjaxResult weChatBinder(@RequestBody WechatBinder binder){
        //校验手机 、 验证码 、unionid
        String phone = binder.getPhone();
        String unionid = binder.getUnionid();
        String verifyCode = binder.getVerifyCode();
        if(phone == null)
            return AjaxResult.error().setMsg("非法访问!");
        if(unionid == null)
            return AjaxResult.error().setMsg("非法访问!");
        if(verifyCode == null)
            return AjaxResult.error().setMsg("非法访问!");
        //手机绑定验证码
        Object obj = redisTemplate.opsForValue().get(phone + BaseConstants.Phone.PHONE_KEY_BIND);
        if(obj == null)
            return AjaxResult.error().setMsg("验证码已过期!");
        String s = obj.toString();
        if(!s.equals(verifyCode))
            return AjaxResult.error().setMsg("验证码输入错误!");

        //通过手机号查询是否存在对应的用户
        User byPhone = userService.findByPhone(phone);
        if (byPhone != null){   //用户存在，判断对应用户的id是否存在于微信用户表中，存在就已经被绑定了，不存在就绑定
            Wxuser one = wxuserService.findByUserid(byPhone.getId());
            if (one != null)
                return AjaxResult.error().setMsg("该手机号已被绑定!");
            else
                executeBind(binder,byPhone.getId());
        }else {     //用户不存在，就构建数据，存入数据库
            PhoneRegister register = new PhoneRegister();
            register.setPhone(phone);
            register.setPassword("111111");
            //告知用户，初始密码为111111
            //MassageUtil.sendMsg(phone,"默认密码：111111");
            Long userid = userService.add(register);
            executeBind(binder,userid);
            byPhone = new User();
            //给对象设置用户名和密码，用于登录
            byPhone.setUsername(phone);
            byPhone.setPassword(register.getPassword());
        }
        //绑定完成以后，就登录
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setPassword(byPhone.getPassword());
        loginDTO.setUsername(byPhone.getUsername());
        loginDTO.setType(BaseConstants.Login.TYPE_USER);
        loginDTO.setAutoLogin(true);
        return logininfoService.account(loginDTO);
    }

    private void executeBind(WechatBinder binder, Long id) {
        Wxuser byUnionid = wxuserService.findByUnionId(binder.getUnionid());
        if (byUnionid == null) {
            throw new BusinessException("非法访问!");
        }
        byUnionid.setUserId(id);
        wxuserService.update(byUnionid);
    }

}
